<template>
  <div class="list-common-table">
    <t-form ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
            <t-col :span="4">
              <t-form-item :label="$t('components.ordersTable.orderName')" name="name">
                <t-input v-model="formData.name" class="form-item-content" type="search"
                  :placeholder="$t('components.ordersTable.orderNamePlaceholder')" :style="{ minWidth: '134px' }" />
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item :label="$t('components.ordersTable.orderStatus')" name="status">
                <t-select v-model="formData.status" class="form-item-content" :options="ORDER_STATUS_OPTIONS"
                  :placeholder="$t('components.ordersTable.orderStatusPlaceholder')" clearable />
              </t-form-item>
            </t-col>
            <t-col :span="4">
              <t-form-item :label="$t('components.ordersTable.orderID')" name="no">
                <t-input v-model="formData.no" class="form-item-content"
                  :placeholder="$t('components.ordersTable.orderIDPlaceholder')" :style="{ minWidth: '134px' }" />
              </t-form-item>
            </t-col>
            <!--            <t-col :span="4">-->
            <!--              <t-form-item :label="$t('components.ordersTable.orderType')" name="type">-->
            <!--                <t-select-->
            <!--                  v-model="formData.type"-->
            <!--                  style="display: inline-block"-->
            <!--                  class="form-item-content"-->
            <!--                  :options="CONTRACT_TYPE_OPTIONS"-->
            <!--                  :placeholder="$t('components.ordersTable.orderTypePlaceholder')"-->
            <!--                  clearable-->
            <!--                />-->
            <!--              </t-form-item>-->
            <!--            </t-col>-->
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }" @click="selectBySome">
            查询
          </t-button>
          <t-button type="reset" variant="base" theme="default" @click="getOrders"> 重置 </t-button>
        </t-col>
      </t-row>
    </t-form>

    <div class="table-container">
      <t-table :data="list" :columns="COLUMNS" :row-key="rowKey" :vertical-align="verticalAlign" :hover="hover"
        :pagination="pagination" :loading="dataLoading" :header-affixed-top="headerAffixedTop"
       >
        <template #status="{ row }">
          <t-tag v-if="row.status === 3" theme="success" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.finish') }}
          </t-tag>
          <t-tag v-if="row.status === 0" theme="warning" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.unpaid') }}
          </t-tag>
          <t-tag v-if="row.status === 1" theme="primary" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.paid') }}
          </t-tag>
          <t-tag v-if="row.status === 2" theme="default" variant="light">
            {{ $t('components.ordersTable.orderStatusEnum.cancelled') }}
          </t-tag>
        </template>
        <!--        <template #contractType="{ row }">-->
        <!--          <p v-if="row.contractType === CONTRACT_TYPES.MAIN">{{ $t('pages.listBase.contractStatusEnum.fail') }}</p>-->
        <!--          <p v-if="row.contractType === CONTRACT_TYPES.SUB">{{ $t('pages.listBase.contractStatusEnum.audit') }}</p>-->
        <!--          <p v-if="row.contractType === CONTRACT_TYPES.SUPPLEMENT">-->
        <!--            {{ $t('pages.listBase.contractStatusEnum.pending') }}-->
        <!--          </p>-->
        <!--        </template>-->
        <!--        <template #paymentType="{ row }">-->
        <!--          <div v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.PAYMENT" class="payment-col">-->
        <!--            {{ $t('pages.listBase.pay') }}<trend class="dashboard-item-trend" type="up" />-->
        <!--          </div>-->
        <!--          <div v-if="row.paymentType === CONTRACT_PAYMENT_TYPES.RECEIPT" class="payment-col">-->
        <!--            {{ $t('pages.listBase.receive') }}<trend class="dashboard-item-trend" type="down" />-->
        <!--          </div>-->
        <!--        </template>-->
        <template #op="slotProps">
          <t-space>
            <t-link theme="primary" @click="handleClickDetail(slotProps.row)"> 详情</t-link>

            <t-link theme="danger" @click="deleteReady(slotProps.row.no) ;visibleDelete=true"> 取消</t-link>
          </t-space>
        </template>
      </t-table>
      <t-dialog v-model:visible="visibleDelete" header="确认取消当前所选订单？"  @confirm="deleteOrder(deleteIdx)"/>
    </div>
  </div>
</template>
<script setup lang="ts">
import { MessagePlugin, PageInfo, PrimaryTableCol, TableRowData } from 'tdesign-vue-next';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import {USER_LIST, userlistType} from "@/pages/user/constants";
import { getList } from '@/api/list';
import Trend from '@/components/trend/index.vue';
import { prefix } from '@/config/global';
import { CONTRACT_PAYMENT_TYPES, CONTRACT_STATUS, CONTRACT_TYPES, ORDER_STATUS } from '@/constants';
import { t } from '@/locales';
import { useSettingStore } from '@/store';
import axios from "axios";
import {UserOrderListType } from "@/pages/user/Orders";
import { UserInfoListType } from "@/pages/user/constants";


interface FormData {
  name: string;
  no: string;
  status?: number;
  type: string;
}
const store = useSettingStore();
const router = useRouter();
const visibleDelete = ref(false);
const ORDER_STATUS_OPTIONS = [
  { value: ORDER_STATUS.UNPAID, label: t('components.ordersTable.orderStatusEnum.unpaid') },
  { value: ORDER_STATUS.FINISH, label: t('components.ordersTable.orderStatusEnum.finish') },
  { value: ORDER_STATUS.CANCELLED, label: t('components.ordersTable.orderStatusEnum.cancelled') },
  { value: ORDER_STATUS.PAID, label: t('components.ordersTable.orderStatusEnum.paid') },
];

const deleteOrder = async (ID: number) => {
  try {
    const response = await axios.delete('/api/user/deleteOrder',
      {
        params: {
          id: ID,
        }
      });
    if (response.data.success) {
      MessagePlugin.success('取消成功');
      getOrders();
    } else {
      MessagePlugin.error('订单状态非待付款，取消失败，请再次确认订单状态');
    }
  } catch (error) {
    console.log(error);
    MessagePlugin.error('请求失败，请稍后重试');
  }

};
// const CONTRACT_TYPE_OPTIONS = [
//   { value: CONTRACT_TYPES.MAIN, label: t('components.commonTable.contractTypeEnum.main') },
//   { value: CONTRACT_TYPES.SUB, label: t('components.commonTable.contractTypeEnum.sub') },
//   { value: CONTRACT_TYPES.SUPPLEMENT, label: t('components.commonTable.contractTypeEnum.supplement') },
// ];
const COLUMNS: PrimaryTableCol[] = [
  {
    title: t('components.ordersTable.orderName'),
    fixed: 'left',
    width: 280,
    ellipsis: true,
    align: 'left',
    colKey: 'name',
  },
  { title: t('components.ordersTable.orderStatus'), colKey: 'status', width: 160 },
  {
    title: t('components.ordersTable.orderID'),
    width: 160,
    ellipsis: true,
    colKey: 'no',
  },

  {
    title: t('components.ordersTable.orderAmount'),
    width: 160,
    ellipsis: true,
    colKey: 'amount',
  },
  {
    align: 'left',
    fixed: 'right',
    width: 160,
    colKey: 'op',
    title: t('components.ordersTable.operation'),
  },
];

const searchForm = {
  name: '',
  no: '',
  type: '',
};

const formData = ref<FormData>({ ...searchForm });
const rowKey = 'index';
const verticalAlign = 'top' as const;
const hover = true;
const ORDER_LIST = ref<UserOrderListType[]>([]);
const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});


const data = ref([]);

const dataLoading = ref(false);

const deleteIdx = ref(-1);

const list = ref([]);


const resetIdx = () => {
  deleteIdx.value = -1;
};

onMounted(() => {
  // fetchData();
  getOrders();
});

const deleteReady = (no:number) => {
  deleteIdx.value = no;

};
const selectBySome = async () => {
  try {
    const response = await axios.get('/api/user/getOrders',{
      params: {
        ordername: formData.value.name,
        orderid: formData.value.no,
        orderstatus: formData.value.status,
      }
    });
    list.value = [];
    if (response.data.success) {
      const orders =  response.data.data.list;
      console.log(orders);
      orders.forEach((od) => {
        list.value.push({
          name: od.ordername,
          status: od.orderstatus,
          no: od.orderid,
          num: od.number,
          date: od.createat,
          amount: `￥${od.orderamount}`, // 格式化金额
        });
      });
    }
    else {
      MessagePlugin.error({
        content: '加载失败'
      });
    }
  } catch (error) {
    console.log(error);
  }
};
const getOrders = async () => {
  try {
    const response = await axios.get('/api/user/getOrders');
    if (response.data.success) {
      list.value = [];
      const orders = response.data.data.list;
      console.log(orders);
      orders.forEach((od) => {
        list.value.push({
          name: od.ordername,
          status: od.orderstatus,
          no: od.orderid,
          num: od.number,
          date: od.createat,
          amount: `￥${od.orderamount}`, // 格式化金额
        });
    });
      pagination.value = {
        ...pagination.value,
        total: orders.length,
      };
    }
    else {
      MessagePlugin.error({
        content: '加载失败'
      });
    }
  } catch (error) {
    console.log(error);
  }
};
// const fetchData = async () => {
//   dataLoading.value = true;
//   try {
//     const { list } = await getList();
//     data.value = list;
//     pagination.value = {
//       ...pagination.value,
//       total: list.length,
//     };
//   } catch (e) {
//     console.log(e);
//   } finally {
//     dataLoading.value = false;
//   }
// };

const onReset = (val: unknown) => {
  console.log(val);
};

const handleClickDetail = (row:userlistType) => {
  router.push({path :'/detail/base',query: { id: row.no, name: row.name, status: row.status, num: row.num, date: row.date, amount: row.amount }});
};
const onSubmit = (val: unknown) => {
  console.log(val);
  console.log(formData.value);
};

const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};
const onCurrentChange = (current: number) => {
  pagination.value.current = current;
};
const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}
</style>
